package com.notes.dao.implement;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import com.notes.dao.UserDao;
import com.notes.model.Item;
import com.notes.model.User;
@Component
public class UserDaoImplement implements UserDao{
	@Resource
	private SessionFactory sessionFactory;
	
	@Override
	public User getUserById(Long userId) {
		Session session = sessionFactory.getCurrentSession();
		Query q = session.createQuery("from User u where userId = :userId");
		q.setLong("userId", userId);
		List result = q.list();
		return ((User)result.get(0));
		
	}
	
	@Override
	public Long login(String userName, String password) {
		
		Session session = sessionFactory.getCurrentSession();
		
		Query q = session.createQuery("from User u where u.userName = :userName and u.password = :password");
		q.setString("userName", userName);
		q.setString("password", password);
		List result = q.list();
		if(result.isEmpty()){
				return null;
		}
		User user = (User) result.get(0);
		return user.getUserId();
		
	}
	
	@Override
	public Long addUser(String name, String password) {
		Session session = sessionFactory.getCurrentSession();
		Query addUserquery = session.createQuery("from User u where u.userName = :userName and u.password = :password");
		addUserquery.setString("userName", name);
		addUserquery.setString("password", password);
		List result = addUserquery.list();
		if(!result.isEmpty()){
			return null;
		}		
		User user = new User();
		user.setUserName(name);
		user.setPassword(password);
		session.save(user);
		return user.getUserId();
	}

	@Override
	public List<Item> getItemByUserId(Long userId) {
		Session session = sessionFactory.getCurrentSession();
		Query q = session.createQuery("from Item where userId = :userId");
		q.setLong("userId", userId);
		List result = q.list();
		return result;		
	}
}
